package com.wajahatkarim3.rdbexplorer.slice;

import com.wajahatkarim3.rdbexplorer.slice.dialog.ConfirmDialog;
import com.wajahatkarim3.rdbexplorer.slice.dialog.ConfirmdialogListener;
import com.wajahatkarim3.rdbexplorer.slice.dialog.PickerDialog;
import com.wajahatkarim3.rdbexplorer.slice.dialog.PickerdialogListener;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.IDialog.ClickedListener;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.rdb.RdbStore;
import ohos.data.resultset.ResultSet;
import ohos.data.resultset.TableResultSet;

import java.util.ArrayList;
import java.util.LinkedList;

import static ohos.agp.utils.LayoutAlignment.BOTTOM;

/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class RdbExplorerAbilitySlice extends AbilitySlice {

    static class IndexInfo
    {
        public static int index = 10;
        public static int numberofpages = 0;
        public static int currentpage = 0;
        public static String table_name="";
        public static ResultSet maincursor;
        public static ArrayList<String> emptytablecolumnnames;
        public static boolean isEmpty;
        public static boolean isCustomQuery;
        public static int colWidth = 200;
        public static int colHeight = 60;
    }

    TableLayout tableLayout;
    DirectionalLayout.LayoutConfig tableRowParams;
    ScrollView hsv;
    ScrollView mainscrollview;
    DirectionalLayout mainLayout;
    Text tvmessage;
    Button previous;
    Button next;
    Text select_table;
    Text tv;
    ShapeElement whiteElement = new ShapeElement();
    ShapeElement blackElement = new ShapeElement();
    ShapeElement buttonElement = new ShapeElement();
    Intent intent;

    public static RdbStore rdbStore;
    static long mLastClickTime = 0L;

    public static void setRdbStore(RdbStore rdbStore) {
        RdbExplorerAbilitySlice.rdbStore = rdbStore;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        this.intent = intent;
        if (rdbStore == null) {
            throw new RuntimeException("RdbStore is null.Please set the RdbStore of RdbExplorerAbilitySlice.");
        }

        whiteElement.setRgbColor(new RgbColor(255, 255, 255));
        blackElement.setRgbColor(new RgbColor(0, 0, 0));
        buttonElement.setRgbColor(new RgbColor(186, 231, 246));

        mainscrollview = new ScrollView(RdbExplorerAbilitySlice.this);
        mainscrollview.setWidth(DependentLayout.LayoutConfig.MATCH_PARENT);
        mainscrollview.setHeight(DependentLayout.LayoutConfig.MATCH_PARENT);

        mainLayout = new DirectionalLayout(RdbExplorerAbilitySlice.this);
        mainLayout.setHeight(DependentLayout.LayoutConfig.MATCH_PARENT);
        mainLayout.setWidth(DependentLayout.LayoutConfig.MATCH_PARENT);
        mainLayout.setMarginLeft(10);
        mainLayout.setMarginRight(10);
        mainLayout.setOrientation(DirectionalLayout.VERTICAL);
        mainLayout.setBackground(whiteElement);

        mainscrollview.addComponent(mainLayout);
        setUIContent(mainscrollview);

        final DirectionalLayout firstrow = new DirectionalLayout(RdbExplorerAbilitySlice.this);
        firstrow.setPadding(0,10,0,20);
        firstrow.setWidth(DependentLayout.LayoutConfig.MATCH_PARENT);
        firstrow.setHeight(DependentLayout.LayoutConfig.MATCH_CONTENT);
        firstrow.setOrientation(DirectionalLayout.HORIZONTAL);

        DirectionalLayout.LayoutConfig firstrowlp = new DirectionalLayout.LayoutConfig(0, 150);
        firstrowlp.weight = 1;

        Text maintext = new Text(RdbExplorerAbilitySlice.this);
        maintext.setText("Select Table");
        maintext.setTextSize(22, Text.TextSizeType.FP);
        select_table=new Text(RdbExplorerAbilitySlice.this);
        select_table.setLayoutConfig(firstrowlp);
        select_table.setText("click here");
        select_table.setTextSize(22, Text.TextSizeType.FP);
        select_table.setTextAlignment(TextAlignment.RIGHT);
        firstrow.addComponent(maintext);
        firstrow.addComponent(select_table);
        mainLayout.addComponent(firstrow);

        ArrayList<ResultSet> alc;
        hsv = new ScrollView(RdbExplorerAbilitySlice.this);
        tableLayout = new TableLayout(RdbExplorerAbilitySlice.this);
        tableLayout.setBackground(blackElement);
        tableLayout.setPadding(1,1,1,1);
        tableLayout.setAlignmentType(TableLayout.ALIGN_EDGES);
        hsv.addComponent(tableLayout);

        final DirectionalLayout secondrow = new DirectionalLayout(RdbExplorerAbilitySlice.this);
        secondrow.setPadding(0,20,0,10);
        secondrow.setOrientation(Component.HORIZONTAL);

        DirectionalLayout.LayoutConfig secondrowlp = new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_PARENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        secondrowlp.weight = 1;

        Text secondrowtext = new Text(RdbExplorerAbilitySlice.this);
        secondrowtext.setText("No. Of Records : ");
        secondrowtext.setTextSize(20, Text.TextSizeType.FP);
        tv =new Text(RdbExplorerAbilitySlice.this);
        tv.setTextSize(20, Text.TextSizeType.FP);
        tv.setLayoutConfig(secondrowlp);
        tv.setMarginLeft(30);

        secondrow.addComponent(secondrowtext);
        secondrow.addComponent(tv);
        secondrow.setVisibility(Component.HIDE);
        mainLayout.addComponent(secondrow);

        final TextField customquerytext = new TextField(this);
        customquerytext.setVisibility(Component.HIDE);
        customquerytext.setTextSize(15, Text.TextSizeType.FP);
        customquerytext.setHint("Enter Your Query here and Click on Submit Query Button .Results will be displayed below");
        mainLayout.addComponent(customquerytext);

        final Button submitQuery = new Button(RdbExplorerAbilitySlice.this);
        submitQuery.setVisibility(Component.HIDE);
        submitQuery.setText("Submit Query");
        submitQuery.setWidth(DirectionalLayout.LayoutConfig.MATCH_PARENT);
        submitQuery.setTextSize(20, Text.TextSizeType.FP);
        submitQuery.setBackground(buttonElement);
        mainLayout.addComponent(submitQuery);

        final Text help = new Text(RdbExplorerAbilitySlice.this);
        help.setText("Click on the row below to update values or delete the tuple");
        help.setTextSize(12, Text.TextSizeType.FP);
        help.setPadding(0,5,0,5);
        help.setVisibility(Component.HIDE);

        final Text spinnertable =new Text(RdbExplorerAbilitySlice.this);
        spinnertable.setVisibility(Component.HIDE);
        spinnertable.setText("Click Here to Change this table");
        spinnertable.setTextSize(20, Text.TextSizeType.FP);
        spinnertable.setTextAlignment(TextAlignment.RIGHT);
        spinnertable.setClickable(true);
        spinnertable.setWidth(DirectionalLayout.LayoutConfig.MATCH_PARENT);

        mainLayout.addComponent(spinnertable);
        mainLayout.addComponent(help);

        hsv.setPadding(0,10,0,10);
        hsv.enableFadeEffect(Component.FadeEffectEnum.FADEEFFECT_SCROLLBAR);
        mainLayout.addComponent(hsv);

        final DirectionalLayout thirdrow = new DirectionalLayout(RdbExplorerAbilitySlice.this);
        previous = new Button(RdbExplorerAbilitySlice.this);
        previous.setText("Previous");
        previous.setWidth(300);
        previous.setTextSize(20, Text.TextSizeType.FP);
        previous.setBackground(buttonElement);
        next = new Button(RdbExplorerAbilitySlice.this);
        next.setText("Next");
        next.setWidth(300);
        next.setTextSize(20, Text.TextSizeType.FP);
        next.setBackground(buttonElement);

        DirectionalLayout.LayoutConfig tvl = new DirectionalLayout.LayoutConfig(0, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        tvl.weight = 1;
        Text tvblank = new Text(this);
        tvblank.setLayoutConfig(tvl);

        thirdrow.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
        thirdrow.setOrientation(DirectionalLayout.HORIZONTAL);
        thirdrow.setPadding(0,10,0,10);
        thirdrow.addComponent(previous);
        thirdrow.addComponent(tvblank);
        thirdrow.addComponent(next);
        thirdrow.setVisibility(Component.HIDE);
        mainLayout.addComponent(thirdrow);

        String Query = "SELECT name _id FROM sqlite_master WHERE type ='table'";
        tvmessage =new Text(RdbExplorerAbilitySlice.this);
        tvmessage.setText("Error Messages will be displayed here");
        tvmessage.setTextSize(18, Text.TextSizeType.FP);
        tvmessage.setVisibility(Component.HIDE);
        mainLayout.addComponent(tvmessage);

        final Button customQuery = new Button(RdbExplorerAbilitySlice.this);
        customQuery.setText("Custom Query");
        customQuery.setTextSize(20, Text.TextSizeType.FP);
        customQuery.setBackground(buttonElement);
        customQuery.setWidth(DirectionalLayout.LayoutConfig.MATCH_PARENT);
        customQuery.setVisibility(Component.HIDE);
        mainLayout.addComponent(customQuery);

        customQuery.setClickedListener(component -> {
            IndexInfo.isCustomQuery=true;
            secondrow.setVisibility(Component.HIDE);
            spinnertable.setVisibility(Component.HIDE);
            help.setVisibility(Component.HIDE);
            customquerytext.setVisibility(Component.VISIBLE);
            submitQuery.setVisibility(Component.VISIBLE);
            customQuery.setVisibility(Component.HIDE);
            if (!select_table.getText().equals("click here") && select_table.getText() != null) {
                customquerytext.setText("select * from "+select_table.getText());
            }
        });

        submitQuery.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
                tableLayout.removeAllComponents();
                customQuery.setVisibility(Component.HIDE);

                ArrayList<ResultSet> alc2;
                String Query10 = customquerytext.getText();

                alc2 = getData(Query10);
                final ResultSet c4 = alc2.get(0);
                ResultSet Message2 = alc2.get(1);
                Message2.goToLastRow();

                ShapeElement element = new ShapeElement();
                if (Message2.getString(0).equalsIgnoreCase("Success")) {
                    element.setRgbColor(RgbColor.fromRgbaInt(0x2ecc71));
                    tvmessage.setBackground(element);
                    tvmessage.setMultipleLine(true);
                    if (c4 != null) {
                        tvmessage.setText("Queru Executed successfully.Number of rows returned :" + c4.getRowCount());
                        if (c4.getRowCount() > 0) {
                            IndexInfo.maincursor = c4;
                            refreshTable(1);
                        }
                    } else {
                        tvmessage.setText("Queru Executed successfully");
                        refreshTable(1);
                    }
                } else {
                    element.setRgbColor(RgbColor.fromRgbaInt(0xe74c3c));
                    tvmessage.setBackground(element);
                    tvmessage.setText("Error:" + Message2.getString(0));
                }
            }
        });

        tableRowParams = new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        tableRowParams.setMargins(0, 0, 2, 0);

        alc = getData(Query);
        final ResultSet c=alc.get(0);
        ResultSet Message =alc.get(1);
        Message.goToLastRow();
        ArrayList<String> tablenames = new ArrayList<>();

        if(c!=null)
        {
            c.goToFirstRow();
            do{
                tablenames.add(c.getString(0));
            }while(c.goToNextRow());
        }

        select_table.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (tablenames.size() > 0 && !isDoubleClick()) {
                    PickerDialog dialog = new PickerDialog(RdbExplorerAbilitySlice.this, new PickerdialogListener() {
                        @Override
                        public void getPickerStrSuccess(String str) {
                            if (str == null && !IndexInfo.isCustomQuery) {
                                secondrow.setVisibility(Component.HIDE);
                                hsv.setVisibility(Component.HIDE);
                                thirdrow.setVisibility(Component.HIDE);
                                spinnertable.setVisibility(Component.HIDE);
                                help.setVisibility(Component.HIDE);
                                tvmessage.setVisibility(Component.HIDE);
                                customquerytext.setVisibility(Component.HIDE);
                                submitQuery.setVisibility(Component.HIDE);
                                customQuery.setVisibility(Component.HIDE);
                            }
                            if (str != null) {
                                secondrow.setVisibility(Component.VISIBLE);
                                spinnertable.setVisibility(Component.VISIBLE);
                                help.setVisibility(Component.VISIBLE);
                                customquerytext.setVisibility(Component.HIDE);
                                submitQuery.setVisibility(Component.HIDE);
                                customQuery.setVisibility(Component.VISIBLE);
                                hsv.setVisibility(Component.VISIBLE);
                                tvmessage.setVisibility(Component.VISIBLE);
                                thirdrow.setVisibility(Component.VISIBLE);
                                IndexInfo.table_name = str;
                                tvmessage.setText("Error Messages will be displayed here");
                                tvmessage.setBackground(whiteElement);
                                tableLayout.removeAllComponents();
                                ArrayList<String> spinnertablevalues = new ArrayList<>();
                                spinnertablevalues.add("Add row to this table");
                                spinnertablevalues.add("Delete this table");
                                spinnertablevalues.add("Drop this table");
                                String Query2 = "select * from " + str;
                                ArrayList<ResultSet> alc2 = getData(Query2);
                                final ResultSet c2 = alc2.get(0);
                                IndexInfo.maincursor = c2;

                                if (c2 != null) {
                                    int counts = c2.getRowCount();
                                    IndexInfo.isEmpty = false;
                                    tv.setText("" + counts);

                                    spinnertable.setClickedListener(new Component.ClickedListener() {
                                        @Override
                                        public void onClick(Component component) {
                                            if (!isDoubleClick()) {
                                                PickerDialog dialog = new PickerDialog(RdbExplorerAbilitySlice.this, new PickerdialogListener() {
                                                    @Override
                                                    public void getPickerStrSuccess(String str) {
                                                        if (str.equals("Drop this table")) {
                                                            RdbExplorerAbilitySlice.this.getUITaskDispatcher().delayDispatch(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    ConfirmDialog dialog = new ConfirmDialog(RdbExplorerAbilitySlice.this, new ConfirmdialogListener() {
                                                                        @Override
                                                                        public void getClickStatus(boolean clickStatus) {
                                                                            if (clickStatus) {
                                                                                String Query6 = "Drop table " + IndexInfo.table_name;
                                                                                ArrayList<ResultSet> aldropt = getData(Query6);
                                                                                ResultSet tempc = aldropt.get(1);
                                                                                tempc.goToLastRow();

                                                                                if (tempc.getString(0).equalsIgnoreCase("Success")) {
                                                                                    ShapeElement element = new ShapeElement();
                                                                                    element.setRgbColor(RgbColor.fromRgbaInt(0x2ecc71));
                                                                                    tvmessage.setBackground(element);
                                                                                    tvmessage.setText(IndexInfo.table_name + "Dropped successfully");
                                                                                    refreshactivity();
                                                                                } else {
                                                                                    ShapeElement element = new ShapeElement();
                                                                                    element.setRgbColor(RgbColor.fromRgbaInt(0xe74c3c));
                                                                                    tvmessage.setBackground(element);
                                                                                    tvmessage.setText("Error:" + tempc.getString(0));
                                                                                }
                                                                            }
                                                                        }
                                                                    }, "Are you sure ?", "Pressing yes will remove " + IndexInfo.table_name + " table from database");
                                                                    dialog.show();
                                                                }
                                                            }, 0);
                                                        }

                                                        if (str.equals("Delete this table")) {
                                                            RdbExplorerAbilitySlice.this.getUITaskDispatcher().delayDispatch(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    ConfirmDialog dialog = new ConfirmDialog(RdbExplorerAbilitySlice.this, new ConfirmdialogListener() {
                                                                        @Override
                                                                        public void getClickStatus(boolean clickStatus) {
                                                                            if (clickStatus) {
                                                                                String Query7 = "Delete  from " + IndexInfo.table_name;
                                                                                ArrayList<ResultSet> aldeletet = getData(Query7);
                                                                                ResultSet tempc = aldeletet.get(1);
                                                                                tempc.goToLastRow();

                                                                                if (tempc.getString(0).equalsIgnoreCase("Success")) {
                                                                                    ShapeElement element = new ShapeElement();
                                                                                    element.setRgbColor(RgbColor.fromRgbaInt(0x2ecc71));
                                                                                    tvmessage.setBackground(element);
                                                                                    tvmessage.setText(IndexInfo.table_name + " table content deleted successfully");
                                                                                    IndexInfo.isEmpty = true;
                                                                                    refreshTable(0);
                                                                                } else {
                                                                                    ShapeElement element = new ShapeElement();
                                                                                    element.setRgbColor(RgbColor.fromRgbaInt(0xe74c3c));
                                                                                    tvmessage.setBackground(element);
                                                                                    tvmessage.setText("Error:" + tempc.getString(0));
                                                                                }
                                                                            }
                                                                        }
                                                                    }, "Are you sure ?", "Clicking on yes will delete all the contents of " + IndexInfo.table_name + " table from database");
                                                                    dialog.show();
                                                                }
                                                            }, 0);
                                                        }

                                                        if (str.equals("Add row to this table")) {
                                                            final LinkedList<Text> addnewrownames = new LinkedList<>();
                                                            final LinkedList<TextField> addnewrowvalues = new LinkedList<>();
                                                            final ScrollView addrowsv = new ScrollView(RdbExplorerAbilitySlice.this);
                                                            ResultSet c4 = IndexInfo.maincursor;

                                                            if (IndexInfo.isEmpty) {
                                                                getcolumnnames();
                                                                for (int i = 0; i < IndexInfo.emptytablecolumnnames.size(); i++) {
                                                                    String cname = IndexInfo.emptytablecolumnnames.get(i);
                                                                    Text tv = new Text(RdbExplorerAbilitySlice.this);
                                                                    tv.setText(cname);
                                                                    addnewrownames.add(tv);
                                                                }
                                                                for (int i = 0; i < addnewrownames.size(); i++) {
                                                                    TextField et = new TextField(RdbExplorerAbilitySlice.this);
                                                                    addnewrowvalues.add(et);
                                                                }
                                                            } else {
                                                                for (int i = 0; i < c4.getColumnCount(); i++) {
                                                                    String cname = c4.getColumnNameForIndex(i);
                                                                    Text tv = new Text(RdbExplorerAbilitySlice.this);
                                                                    tv.setText(cname);
                                                                    addnewrownames.add(tv);
                                                                }
                                                                for (int i = 0; i < addnewrownames.size(); i++) {
                                                                    TextField et = new TextField(RdbExplorerAbilitySlice.this);
                                                                    addnewrowvalues.add(et);
                                                                }
                                                            }

                                                            final DependentLayout addnewlayout = new DependentLayout(RdbExplorerAbilitySlice.this);
                                                            DependentLayout.LayoutConfig addnewparams = new DependentLayout.LayoutConfig(DependentLayout.LayoutConfig.MATCH_PARENT, DependentLayout.LayoutConfig.MATCH_CONTENT);
                                                            addnewparams.addRule(DependentLayout.LayoutConfig.ALIGN_PARENT_TOP);
                                                            addnewlayout.setLayoutConfig(addnewparams);
                                                            addnewlayout.setMarginsLeftAndRight(20, 20);

                                                            for (int i = 0; i < addnewrownames.size(); i++) {
                                                                Text tv = addnewrownames.get(i);
                                                                TextField et = addnewrowvalues.get(i);
                                                                int t = i + 400;
                                                                int k = i + 500;
                                                                int lid = i + 600;

                                                                tv.setId(t);
                                                                tv.setTextSize(15, Text.TextSizeType.FP);
                                                                tv.setTextColor(Color.BLACK);

                                                                ShapeElement element = new ShapeElement();
                                                                element.setRgbColor(RgbColor.fromRgbaInt(0xF2F2F2));
                                                                et.setBackground(element);
                                                                et.setTextSize(15, Text.TextSizeType.FP);
                                                                et.setTextColor(Color.BLACK);
                                                                et.setId(k);

                                                                final DirectionalLayout ll = new DirectionalLayout(RdbExplorerAbilitySlice.this);
                                                                ll.setOrientation(Component.HORIZONTAL);
                                                                ll.setWidth(DirectionalLayout.LayoutConfig.MATCH_PARENT);
                                                                DirectionalLayout.LayoutConfig tvl = new DirectionalLayout.LayoutConfig(0, 100);
                                                                tvl.weight = 1;
                                                                et.setLayoutConfig(tvl);
                                                                et.setMarginLeft(20);
                                                                ll.addComponent(tv);
                                                                ll.addComponent(et);
                                                                ll.setId(lid);
                                                                DependentLayout.LayoutConfig rll = new DependentLayout.LayoutConfig(DependentLayout.LayoutConfig.MATCH_PARENT, DependentLayout.LayoutConfig.MATCH_CONTENT);
                                                                rll.addRule(DependentLayout.LayoutConfig.BELOW, ll.getId() - 1);
                                                                rll.setMargins(0, 20, 0, 0);
                                                                addnewlayout.addComponent(ll, rll);
                                                            }
                                                            addnewlayout.setBackground(whiteElement);
                                                            addrowsv.setLayoutConfig(addnewparams);
                                                            addrowsv.addComponent(addnewlayout);

                                                            RdbExplorerAbilitySlice.this.getUITaskDispatcher().delayDispatch(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    CommonDialog commonDialog = new CommonDialog(RdbExplorerAbilitySlice.this);
                                                                    commonDialog.setTitleText(" values");
                                                                    commonDialog.siteRemovable(false);
                                                                    commonDialog.setContentCustomComponent(addrowsv);
                                                                    commonDialog.setButton(0, "Add",
                                                                            new ClickedListener() {
                                                                                @Override
                                                                                public void onClick(IDialog iDialog, int which) {
                                                                                    IndexInfo.index = 10;
                                                                                    String Query4 = "Insert into " + IndexInfo.table_name + " (";
                                                                                    for (int i = 0; i < addnewrownames.size(); i++) {
                                                                                        Text tv = addnewrownames.get(i);
                                                                                        tv.getText();
                                                                                        if (i == addnewrownames.size() - 1) {
                                                                                            Query4 = Query4 + tv.getText();
                                                                                        } else {
                                                                                            Query4 = Query4 + tv.getText() + ", ";
                                                                                        }
                                                                                    }
                                                                                    Query4 = Query4 + " ) VALUES ( ";
                                                                                    for (int i = 0; i < addnewrownames.size(); i++) {
                                                                                        TextField et = addnewrowvalues.get(i);
                                                                                        et.getText();
                                                                                        if (i == addnewrownames.size() - 1) {
                                                                                            Query4 = Query4 + "'" + et.getText() + "' ) ";
                                                                                        } else {
                                                                                            Query4 = Query4 + "'" + et.getText() + "' , ";
                                                                                        }
                                                                                    }

                                                                                    ArrayList<ResultSet> altc = getData(Query4);
                                                                                    ResultSet tempc = altc.get(1);
                                                                                    tempc.goToLastRow();

                                                                                    if (tempc.getString(0).equalsIgnoreCase("Success")) {
                                                                                        ShapeElement element = new ShapeElement();
                                                                                        element.setRgbColor(RgbColor.fromRgbaInt(0x2ecc71));
                                                                                        tvmessage.setBackground(element);
                                                                                        tvmessage.setText("New Row added succesfully to " + IndexInfo.table_name);
                                                                                        refreshTable(0);
                                                                                    } else {
                                                                                        ShapeElement element = new ShapeElement();
                                                                                        element.setRgbColor(RgbColor.fromRgbaInt(0xe74c3c));
                                                                                        tvmessage.setBackground(element);
                                                                                        tvmessage.setText("Error:" + tempc.getString(0));
                                                                                    }
                                                                                    commonDialog.destroy();
                                                                                }
                                                                            });
                                                                    commonDialog.setButton(1, "close",
                                                                            new ClickedListener() {
                                                                                @Override
                                                                                public void onClick(IDialog iDialog, int which) {
                                                                                    commonDialog.destroy();
                                                                                }
                                                                            });
                                                                    commonDialog.show();
                                                                }
                                                            }, 0);
                                                        }
                                                    }
                                                }, spinnertablevalues, 0);
                                                dialog.setAlignment(BOTTOM);
                                                dialog.show();
                                            }
                                        }
                                    });

                                    tableLayout.setColumnCount(c2.getColumnCount());
                                    tableLayout.setRowCount(c2.getRowCount()+1);
                                    for (int k = 0; k < c2.getColumnCount(); k++) {
                                        final Text tableheadercolums = new Text(RdbExplorerAbilitySlice.this);
                                        tableheadercolums.setBackground(whiteElement);
                                        tableheadercolums.setPadding(0, 0, 4, 3);
                                        tableheadercolums.setText("" + c2.getColumnNameForIndex(k));
                                        tableheadercolums.setTextSize(15, Text.TextSizeType.FP);
                                        tableheadercolums.setTextColor(Color.BLACK);
                                        tableheadercolums.setWidth(IndexInfo.colWidth);
                                        tableheadercolums.setMultipleLine(true);
                                        tableheadercolums.setMarginLeft(1);
                                        tableheadercolums.setMarginTop(1);
                                        tableheadercolums.setMarginBottom(1);
                                        tableLayout.addComponent(tableheadercolums);
                                    }
                                    c2.goToFirstRow();
                                    paginatetable();
                                } else {
                                    help.setVisibility(Component.HIDE);
                                    tableLayout.removeAllComponents();
                                    getcolumnnames();
                                    DirectionalLayout tableheader2 = new DirectionalLayout(RdbExplorerAbilitySlice.this);
                                    tableheader2.setBackground(blackElement);
                                    tableheader2.setPadding(0, 2, 0, 2);

                                    DirectionalLayout cell = new DirectionalLayout(RdbExplorerAbilitySlice.this);
                                    cell.setBackground(whiteElement);
                                    cell.setLayoutConfig(tableRowParams);
                                    final Text tableheadercolums = new Text(RdbExplorerAbilitySlice.this);

                                    tableheadercolums.setPadding(0, 0, 4, 3);
                                    tableheadercolums.setText("   Table   Is   Empty   ");
                                    tableheadercolums.setTextSize(30, Text.TextSizeType.FP);
                                    tableheadercolums.setTextColor(Color.RED);

                                    cell.addComponent(tableheadercolums);
                                    tableheader2.addComponent(cell);
                                    tableLayout.addComponent(tableheader2);
                                    tv.setText("" + 0);
                                }
                                select_table.setText(str);
                            }
                        }
                    }, tablenames, 0);
                    dialog.setAlignment(BOTTOM);
                    dialog.show();
                }
            }
        });
    }

    public void getcolumnnames() {
        ArrayList<ResultSet> alc3=getData("PRAGMA table_info("+ IndexInfo.table_name+")");
        ResultSet c5=alc3.get(0);
        IndexInfo.isEmpty=true;

        if(c5!=null) {
            ArrayList<String> emptytablecolumnnames= new ArrayList<>();
            c5.goToFirstRow();
            do {
                emptytablecolumnnames.add(c5.getString(1));
            } while(c5.goToNextRow());
            IndexInfo.emptytablecolumnnames=emptytablecolumnnames;
        }
    }

    public void updateDeletePopup(int rowId) {
        ResultSet c2= IndexInfo.maincursor;
        ArrayList<String> spinnerArray = new ArrayList<>();
        spinnerArray.add("Update this row");
        spinnerArray.add("Delete this row");

        ArrayList<String> value_string = new ArrayList<>();
        final LinkedList<Text> columnames = new LinkedList<>();
        final LinkedList<TextField> columvalues = new LinkedList<>();

        for(int i=0;i<c2.getColumnCount();i++) {
            String cname = c2.getColumnNameForIndex(i);
            Text tv = new Text(RdbExplorerAbilitySlice.this);
            tv.setText(cname);
            columnames.add(tv);
        }

        for(int i=0;i<columnames.size();i++) {
            c2.goToRow(rowId);
            String cv = c2.getString(i);
            TextField et = new TextField(RdbExplorerAbilitySlice.this);
            value_string.add(cv);
            et.setText(cv);
            columvalues.add(et);
        }

        int lastrid = 0;
        final DependentLayout lp = new DependentLayout(RdbExplorerAbilitySlice.this);
        lp.setBackground(whiteElement);
        DependentLayout.LayoutConfig lay = new DependentLayout.LayoutConfig(DependentLayout.LayoutConfig.MATCH_PARENT, DependentLayout.LayoutConfig.MATCH_CONTENT);
        lay.addRule(DependentLayout.LayoutConfig.ALIGN_PARENT_TOP);
        lp.setLayoutConfig(lay);
        lp.setMarginsLeftAndRight(20,20);

        final ScrollView updaterowsv =new ScrollView(RdbExplorerAbilitySlice.this);
        DirectionalLayout lcrud = new DirectionalLayout(RdbExplorerAbilitySlice.this);
        DirectionalLayout.LayoutConfig paramcrudtext = new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        paramcrudtext.setMargins(0, 20, 0, 0);
        final Text crud_dropdown = new Text(RdbExplorerAbilitySlice.this);
        crud_dropdown.setClickable(true);
        crud_dropdown.setText("Click Here to Change this row");
        crud_dropdown.setTextSize(20, Text.TextSizeType.FP);
        lcrud.setId(299);
        lcrud.addComponent(crud_dropdown,paramcrudtext);

        crud_dropdown.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                PickerDialog dialog=new PickerDialog(RdbExplorerAbilitySlice.this, new PickerdialogListener() {
                    @Override
                    public void getPickerStrSuccess(String str) {
                        crud_dropdown.setText(str);
                    }
                }, spinnerArray, 0);
                dialog.setAlignment(BOTTOM);
                dialog.show();
            }
        });

        DependentLayout.LayoutConfig rlcrudparam = new DependentLayout.LayoutConfig(DependentLayout.LayoutConfig.MATCH_PARENT, DependentLayout.LayoutConfig.MATCH_CONTENT);
        rlcrudparam.addRule(DependentLayout.LayoutConfig.BELOW,lastrid);
        lp.addComponent(lcrud, rlcrudparam);

        for(int i=0;i<columnames.size();i++) {
            Text tv =columnames.get(i);
            TextField et=columvalues.get(i);
            int t = i+100;
            int k = i+200;
            int lid = i+300;

            tv.setId(t);
            tv.setTextColor(Color.BLACK);
            tv.setTextSize(15, Text.TextSizeType.FP);
            ShapeElement element1 = new ShapeElement();
            element1.setRgbColor(RgbColor.fromRgbaInt(0xF2F2F2));
            et.setBackground(element1);
            et.setTextSize(15, Text.TextSizeType.FP);
            et.setTextColor(Color.BLACK);
            et.setId(k);
            final DirectionalLayout ll = new DirectionalLayout(RdbExplorerAbilitySlice.this);
            ll.setOrientation(Component.HORIZONTAL);
            ll.setBackground(whiteElement);
            ll.setId(lid);
            DirectionalLayout.LayoutConfig lpp = new DirectionalLayout.LayoutConfig(0, 100);
            lpp.weight = 1;
            et.setLayoutConfig(lpp);
            et.setMarginLeft(20);
            ll.addComponent(tv);
            ll.addComponent(et);

            DependentLayout.LayoutConfig rll = new DependentLayout.LayoutConfig(DependentLayout.LayoutConfig.MATCH_PARENT, DependentLayout.LayoutConfig.MATCH_CONTENT);
            rll.addRule(DependentLayout.LayoutConfig.BELOW,ll.getId()-1 );
            rll.setMargins(0, 20, 0, 0);
            lp.addComponent(ll, rll);
        }

        updaterowsv.setLayoutConfig(lay);
        updaterowsv.addComponent(lp);
        RdbExplorerAbilitySlice.this.getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                CommonDialog commonDialog = new CommonDialog(RdbExplorerAbilitySlice.this);
                commonDialog.setTitleText(" values");
                commonDialog.siteRemovable(false);
                commonDialog.setContentCustomComponent(updaterowsv);
                commonDialog.setButton(0, "Ok",
                    new IDialog.ClickedListener() {
                        @Override
                        public void onClick(IDialog iDialog, int which) {
                            if(crud_dropdown.getText().equalsIgnoreCase("Update this row")) {
                                String Query3="UPDATE "+ IndexInfo.table_name+" SET ";

                                for(int i=0;i<columnames.size();i++) {
                                    Text tvc = columnames.get(i);
                                    TextField etc = columvalues.get(i);

                                    if(!etc.getText().equals("null")) {
                                        Query3=Query3+tvc.getText()+" = ";
                                        if(i==columnames.size()-1) {
                                            Query3=Query3+"'"+etc.getText()+"'";
                                        } else {
                                            Query3=Query3+"'"+etc.getText()+"' , ";
                                        }
                                    }
                                }

                                Query3=Query3+" where ";
                                for(int i=0;i<columnames.size();i++) {
                                    Text tvc = columnames.get(i);
                                    if(!value_string.get(i).equals("null")) {
                                        Query3=Query3+tvc.getText()+" = ";
                                        if(i==columnames.size()-1) {
                                            Query3=Query3+"'"+value_string.get(i)+"' ";
                                        } else {
                                            Query3=Query3+"'"+value_string.get(i)+"' and ";
                                        }
                                    }
                                }

                                ArrayList<ResultSet> aluc=getData(Query3);
                                ResultSet tempc=aluc.get(1);
                                tempc.goToLastRow();

                                if(tempc.getString(0).equalsIgnoreCase("Success")) {
                                    ShapeElement element = new ShapeElement();
                                    element.setRgbColor(RgbColor.fromRgbaInt(0x2ecc71));
                                    tvmessage.setBackground(element);
                                    tvmessage.setText(IndexInfo.table_name+" table Updated Successfully");
                                    refreshTable(0);
                                } else {
                                    ShapeElement element = new ShapeElement();
                                    element.setRgbColor(RgbColor.fromRgbaInt(0xe74c3c));
                                    tvmessage.setBackground(element);
                                    tvmessage.setText("Error:"+tempc.getString(0));
                                }
                            }

                            if(crud_dropdown.getText().equalsIgnoreCase("Delete this row")) {
                                String Query5="DELETE FROM "+ IndexInfo.table_name+" WHERE ";

                                for(int i=0;i<columnames.size();i++) {
                                    Text tvc = columnames.get(i);
                                    if(!value_string.get(i).equals("null")) {
                                        Query5=Query5+tvc.getText()+" = ";
                                        if(i==columnames.size()-1) {
                                            Query5=Query5+"'"+value_string.get(i)+"' ";
                                        } else {
                                            Query5=Query5+"'"+value_string.get(i)+"' and ";
                                        }
                                    }
                                }

                                getData(Query5);

                                ArrayList<ResultSet> aldc=getData(Query5);
                                ResultSet tempc=aldc.get(1);
                                tempc.goToLastRow();

                                if(tempc.getString(0).equalsIgnoreCase("Success")) {
                                    ShapeElement element = new ShapeElement();
                                    element.setRgbColor(RgbColor.fromRgbaInt(0x2ecc71));
                                    tvmessage.setBackground(element);
                                    tvmessage.setText("Row deleted from "+ IndexInfo.table_name+" table");
                                    refreshTable(0);
                                } else {
                                    ShapeElement element = new ShapeElement();
                                    element.setRgbColor(RgbColor.fromRgbaInt(0xe74c3c));
                                    tvmessage.setBackground(element);
                                    tvmessage.setText("Error:"+tempc.getString(0));
                                }
                            }
                            commonDialog.destroy();
                        }
                    });
                commonDialog.setButton(1,"close",
                    new IDialog.ClickedListener() {
                        @Override
                        public void onClick(IDialog iDialog, int which) {
                            commonDialog.destroy();
                        }
                    });
                commonDialog.show();
            }
        }, 0);
    }

    public void refreshactivity() {
        terminate();
        startAbility(this.intent);
    }

    public void refreshTable(int d ) {
        ResultSet c3=null;
        tableLayout.removeAllComponents();
        if(d==0) {
            String Query8 = "select * from "+ IndexInfo.table_name;
            ArrayList<ResultSet> alc3=getData(Query8);
            c3=alc3.get(0);
            IndexInfo.maincursor=c3;
        }
        if(d==1) {
            c3= IndexInfo.maincursor;
        }

        if(c3!=null) {
            int counts = c3.getRowCount();
            tv.setText(""+counts);

            tableLayout.setRowCount(c3.getRowCount());
            tableLayout.setColumnCount(c3.getColumnCount());

            for(int k=0;k<c3.getColumnCount();k++) {
                final Text tableheadercolums = new Text(RdbExplorerAbilitySlice.this);
                tableheadercolums.setBackground(whiteElement);
                tableheadercolums.setPadding(0, 0, 4, 3);
                tableheadercolums.setText(""+c3.getColumnNameForIndex(k));
                tableheadercolums.setTextColor(Color.BLACK);
                tableheadercolums.setWidth(IndexInfo.colWidth);
                tableheadercolums.setMultipleLine(true);
                tableheadercolums.setTextSize(15, Text.TextSizeType.FP);
                tableheadercolums.setMarginLeft(1);
                tableheadercolums.setMarginTop(1);
                tableheadercolums.setMarginBottom(1);
                tableLayout.addComponent(tableheadercolums);
            }
            c3.goToFirstRow();
            paginatetable();
        } else {
            DirectionalLayout tableheader2 = new DirectionalLayout(RdbExplorerAbilitySlice.this);
            tableheader2.setBackground(blackElement);
            tableheader2.setPadding(0, 2, 0, 2);

            DirectionalLayout cell = new DirectionalLayout(RdbExplorerAbilitySlice.this);
            cell.setBackground(whiteElement);
            cell.setLayoutConfig(tableRowParams);

            final Text tableheadercolums = new Text(RdbExplorerAbilitySlice.this);
            tableheadercolums.setPadding(0, 0, 4, 3);
            tableheadercolums.setText("   Table   Is   Empty   ");
            tableheadercolums.setTextSize(30, Text.TextSizeType.FP);
            tableheadercolums.setTextColor(Color.RED);
            cell.addComponent(tableheadercolums);
            tableheader2.addComponent(cell);
            tableLayout.addComponent(tableheader2);
            tv.setText(""+0);
        }
    }

    public void paginatetable() {
        final ResultSet c3 = IndexInfo.maincursor;
        if (c3.getRowCount() <= IndexInfo.index) {
            IndexInfo.numberofpages=1;
        } else {
            if (c3.getRowCount() % IndexInfo.index == 0) {
                IndexInfo.numberofpages = c3.getRowCount() / IndexInfo.index;
            } else {
                IndexInfo.numberofpages = c3.getRowCount() / IndexInfo.index + 1;
            }
        }
        IndexInfo.currentpage=1;
        c3.goToFirstRow();
        int currentrow=0;

        do {
            for(int j=0 ;j<c3.getColumnCount();j++) {
                final Text columsView = new Text(RdbExplorerAbilitySlice.this);
                String column_data;
                try{
                    column_data = c3.getString(j);
                } catch(Exception e) {
                    throw new RuntimeException(e);
                }
                columsView.setText(column_data);
                columsView.setTextColor(Color.BLACK);
                columsView.setBackground(whiteElement);
                columsView.setTextSize(15, Text.TextSizeType.FP);
                columsView.setPadding(0, 0, 4, 3);
                columsView.setMarginRight(1);
                columsView.setMarginTop(1);
                columsView.setMarginBottom(1);
                columsView.setMultipleLine(true);
                columsView.setHeight(IndexInfo.colHeight);
                columsView.setScrollable(true);
                columsView.setWidth(IndexInfo.colWidth);
                columsView.setTag(currentrow);
                tableLayout.addComponent(columsView);

                int finalCurrentrow = currentrow;
                columsView.setClickedListener(new Component.ClickedListener(){
                    @Override
                    public void onClick(Component component) {
                        updateDeletePopup((IndexInfo.currentpage - 1) * IndexInfo.index + finalCurrentrow);
                    }
                });
            }
            currentrow=currentrow+1;
        }while(c3.goToNextRow()&&currentrow<IndexInfo.index);

        previous.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                int tobestartindex=(IndexInfo.currentpage-2)*IndexInfo.index;

                if(IndexInfo.currentpage==1) {
                    new ToastDialog(RdbExplorerAbilitySlice.this).setText("This is the first page").setDuration(3500).show();
                } else {
                    IndexInfo.currentpage= IndexInfo.currentpage-1;
                    c3.goToRow(tobestartindex);
                    boolean decider=true;

                    for(int i=c3.getColumnCount();i<tableLayout.getChildCount();i++) {
                        Text columsView = (Text) tableLayout.getComponentAt(i);
                        columsView.setVisibility(Component.VISIBLE);
                        columsView.setMultipleLine(true);
                        columsView.setHeight(IndexInfo.colHeight);
                        columsView.setScrollable(true);
                        columsView.setText("" + c3.getString(i%c3.getColumnCount()));
                        if (!decider) {
                            columsView.setVisibility(Component.HIDE);
                        }
                        if (i != c3.getColumnCount() && (i+1)%c3.getColumnCount() == 0) {
                            decider=!c3.isAtLastRow();
                            if(!c3.isAtLastRow()){c3.goToNextRow();}
                        }
                    }
                }
            }
        });

        next.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(IndexInfo.currentpage>= IndexInfo.numberofpages) {
                    new ToastDialog(RdbExplorerAbilitySlice.this).setText("This is the last page").setDuration(3500).show();
                } else {
                    c3.goToRow(IndexInfo.currentpage*IndexInfo.index);
                    boolean decider=true;

                    for (int i=c3.getColumnCount();i<tableLayout.getChildCount();i++) {
                        Text columsView = (Text) tableLayout.getComponentAt(i);
                        columsView.setVisibility(Component.VISIBLE);
                        columsView.setMultipleLine(true);
                        columsView.setHeight(IndexInfo.colHeight);
                        columsView.setScrollable(true);
                        columsView.setText("" + c3.getString(i%c3.getColumnCount()));
                        if (!decider) {
                            columsView.setVisibility(Component.HIDE);
                        }
                        if (i != c3.getColumnCount() && (i+1)%c3.getColumnCount() == 0) {
                            decider=!c3.isAtLastRow();
                            if(!c3.isAtLastRow()){c3.goToNextRow();}
                        }
                    }
                    IndexInfo.currentpage= IndexInfo.currentpage+1;
                }
            }
        });
    }

    public ArrayList<ResultSet> getData(String Query){
        String[] columns = new String[] { "mesage" };
        ArrayList<ResultSet> alc = new ArrayList<>(2);
        TableResultSet Cursor2= new TableResultSet(columns);
        alc.add(null);
        alc.add(null);

        try{
            ResultSet c = rdbStore.querySql(Query, null);
            Cursor2.addRow(new Object[] { "Success" });
            alc.set(1,Cursor2);

            if (null != c && c.getRowCount() > 0) {
                alc.set(0,c);
                c.goToFirstRow();
                return alc ;
            }
            return alc;
        } catch(Exception ex) {
            ex.printStackTrace();
            Cursor2.addRow(new Object[] { ""+ex.getMessage() });
            alc.set(1,Cursor2);
            return alc;
        }
    }

    private boolean isDoubleClick() {
        final long MIN_CLICK_INTERVAL=600;
        long currentClickTime=System.currentTimeMillis();
        long elapsedTime=currentClickTime-mLastClickTime;
        mLastClickTime=currentClickTime;

        return (elapsedTime<=MIN_CLICK_INTERVAL);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

}
